package com.yangxiangrice.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangxiangrice.pojo.*;
import com.yangxiangrice.service.AgItemListingService;
import com.yangxiangrice.service.AgItemsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @author: shixiaojian
 * @date: 2021年11月19日 13:56
 */
@Controller
@RequestMapping("/agitemlisting")
@CrossOrigin
@Slf4j
public class AgItemListingController {
    @Autowired
    AgItemListingService agItemListingService;

    @Autowired
    AgItemsService agItemsService;

    @GetMapping(value = "/listpage")
    @ResponseBody
    public Result listpage(@RequestParam("page") int page,
                           @RequestParam("limit") int limit) {
        Result<IPage> result = new Result<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.ne("parentAgItemId", 0);
        IPage<AgItems> agItemsIPage = agItemsService.seletePage(new Page<>(page, limit), wrapper);
        return result.ok(agItemsIPage);
    }

    @GetMapping(value = "/list")
    @ResponseBody
    public Result list(@RequestParam(value = "agItemId")Integer agItemId)
    {
        Result<List> result = new Result<>();
        Subject subject = SecurityUtils.getSubject();
        String phone = subject.getPrincipal().toString();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.orderByDesc("createtime");
        Map<String, String> map = new HashMap<>();
        map.put("agItemId", agItemId.toString());
        map.put("relatedPerson", phone);
        wrapper.allEq(map);
        List<AgItemListing> list = agItemListingService.list(wrapper);
        if (!list.isEmpty()) {
            result.ok(list);
        }else{
            result.fail("没有相关数据");
        }
        return result;
    }

    @PostMapping(value = "/save")
    @ResponseBody
    public Result save(@RequestParam(value = "inOrOut") Integer inOrOut,
                       @RequestBody AgItemListing agItemListing) {
        Result<Boolean> result = new Result<>();
        Subject subject = SecurityUtils.getSubject();
        String phone = subject.getPrincipal().toString();
        if (inOrOut == 1) {
            agItemListing.setTradeType(0);
        } else {
            agItemListing.setTradeType(3);
            Integer purchase = agItemListingService.getPurchaseNum(agItemListing.getAgItemName(),phone);
            Integer consume = agItemListingService.getConsumeNum(agItemListing.getAgItemName(),phone);
            if (ObjectUtil.isEmpty(consume)) {
                consume = 0;
            }
            if (ObjectUtil.isEmpty(purchase)) {
                return result.fail("尚未购买该农资，请先购买再使用");
            }else if (purchase < (consume+agItemListing.getQuantity()) ){
                return result.fail("可使用数量不足，请重新输入");
            }
        }
        agItemListing.setCreatetime(new Timestamp(System.currentTimeMillis()));
        agItemListing.setRelatedPerson(phone);
        boolean tag = agItemListingService.save(agItemListing);
        if (tag) {
            result.ok(tag);
        } else {
            result.fail("保存失败");
        }
        return result;
    }

    @PostMapping(value = "/delete")
    @ResponseBody
    public Result delete(@RequestParam(value = "recId") Integer recId) {
        Result<Boolean> result = new Result<>();
        boolean tag = agItemListingService.removeById(recId);
        if (tag) {
            result.ok(tag);
        } else {
            result.fail("删除失败");
        }
        return result;
    }

    @PostMapping(value = "/deleteBatch")
    @ResponseBody
    public Result deleteBatch(@RequestBody int[] ids) {
        ArrayList<Integer> list = new ArrayList<>();
        Result<Boolean> result = new Result<>();
        for (int id : ids) {
            list.add(id);
        }
        boolean tag = agItemListingService.removeByIds(list);
        if (tag) {
            result.ok(tag);
        } else {
            result.fail("删除失败");
        }
        return result;
    }

    @RequestMapping(value = "/search")
    @ResponseBody
    public Result search(@RequestParam("input") String input,
                         @RequestParam("page") int page,
                         @RequestParam("limit") int limit) {
        Result<IPage> result = new Result<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("agItemName",input);
        wrapper.ne("parentAgItemId", 0);
        IPage<AgItems> agItemsIPage = agItemsService.seletePage(new Page<>(page, limit), wrapper);
        if (ObjectUtil.isEmpty(agItemsIPage)) {
            result.fail("未找到符合条件的数据");
        }else{
            result.ok(agItemsIPage);
        }
        return result;
    }

    @GetMapping(value = "/getAgItemNameOptions")
    @ResponseBody
    public Result getAgItemNameOptions() {
        Result<List> result = new Result();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("agItemId", "agItemName").ne("parentAgItemId", 0);
        List list = agItemsService.list(wrapper);
        return result.ok(list);
    }

    @GetMapping(value = "/getagitemdata")
    @ResponseBody
    public Result getagitemdata() {
        Result<List> result = new Result();
        Subject subject = SecurityUtils.getSubject();
        String phone = subject.getPrincipal().toString();
        ArrayList<EchartData> res = new ArrayList<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("DISTINCT agItemName");
        wrapper.eq("relatedPerson", phone);
        List<AgItemListing> list = agItemListingService.list(wrapper);
        EchartData data = null;
        for (AgItemListing o : list) {
            data = new EchartData();
            String agItemName = o.getAgItemName();
            data.setName(agItemName);
            Integer purchase = agItemListingService.getPurchaseNum(agItemName,phone);
            if (!ObjectUtil.isEmpty(purchase)) {
                data.setPurchase(purchase);
            }
            Integer consume = agItemListingService.getConsumeNum(agItemName,phone);
            if (!ObjectUtil.isEmpty(consume)) {
                data.setConsume(consume);
            }
            res.add(data);
        }
        result.ok(res);
        return result;
    }

    @GetMapping(value = "/getadminagitemdata")
    @ResponseBody
    public Result getadminagitemdata() {
        Result<List> result = new Result();
        Subject subject = SecurityUtils.getSubject();
        String phone = subject.getPrincipal().toString();
        ArrayList<EchartData> res = new ArrayList<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("DISTINCT agItemName");
        List<AgItemListing> list = agItemListingService.list(wrapper);
        EchartData data = null;
        for (AgItemListing o : list) {
            data = new EchartData();
            String agItemName = o.getAgItemName();
            data.setName(agItemName);
            Integer purchase = agItemListingService.getPurchaseNum(agItemName,phone);
            if (!ObjectUtil.isEmpty(purchase)) {
                data.setPurchase(purchase);
            }
            Integer consume = agItemListingService.getConsumeNum(agItemName,phone);
            if (!ObjectUtil.isEmpty(consume)) {
                data.setConsume(consume);
            }
            res.add(data);
        }
        result.ok(res);
        return result;
    }
}
